package cn.kailangtu.dataspot.total;

import android.graphics.Color;
import android.util.Log;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;

import org.json.JSONObject;
import org.litepal.LitePal;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import cn.kailangtu.commonevents.eventEntity.TotalMainDataChangedEvent;
import cn.kailangtu.commonevents.eventEntity.TotalPopDataChangedEvent;
import cn.kailangtu.commontools.APPSPUtils;
import cn.kailangtu.commontools.LineChatUtils;
import cn.kailangtu.commontools.MyCalendar;
import cn.kailangtu.dataspot.db.NewTotalDataEntity;

public class RealViewTotalData {


    LineDataSet setVoltage ;
    LineDataSet setElectricA,setElectricB,setElectricC ;
    LineChart lineChartVoltage,lineChartElectric;
    LineData lineDataVoltage,lineDataElectric;
    YAxis leftyAxisElectric,rightAxisElectric,leftyAxisVoltage,rightAxisVoltage;

    int defaultWidthVoltage = 0;
    int defaultWidthElectric = 0;
    int defaultLeftVoltage = 0;
    int defaultLeftElectric = 0;
    int currentWidthVoltage = 0;
    int currentWidthElectric = 0;
    int currentLeftVoltage= 0;
    int currentLeftElectric = 0;

    public RealViewTotalData(LineChart lcVoltage,LineChart lcElectric)
    {
        this.lineChartVoltage = lcVoltage;
        this.lineChartElectric = lcElectric;

        resetParams();
    }

    public void resetParams()
    {
        defaultWidthVoltage = this.lineChartVoltage.getLayoutParams().width;
        defaultWidthElectric = this.lineChartElectric.getLayoutParams().width;
        defaultLeftVoltage = ((ViewGroup.MarginLayoutParams)this.lineChartVoltage.getLayoutParams()).leftMargin;
        defaultLeftElectric = ((ViewGroup.MarginLayoutParams)this.lineChartElectric.getLayoutParams()).leftMargin;

        currentWidthVoltage = defaultWidthVoltage;
        currentWidthElectric = defaultWidthElectric;


        Log.d("RealViewTotalData","VO LEFT:"+defaultLeftVoltage);
        Log.d("RealViewTotalData","EL LEFT:"+defaultLeftElectric);
        Log.d("RealViewTotalData==>ResetParams:",defaultWidthVoltage+"  ||   "+defaultWidthElectric);
    }


    public  void resetData(TotalMainDataChangedEvent event){
        if(!isFinding)
        {
            resetData(event.getMaxVoltageValue(),event.getMaxElectricValue(),event.getVoltageValues(),event.getElectricValueA(),event.getElectricValueB(),event.getElectricValueC());
        }

    }

    public void resetData(int maxVoltageValue,int maxElectricValue, int[] voltageValues,int[] electricA,int[] electricB,int[] electricC)
    {
        if(setVoltage != null)
        {
            int cha = maxVoltageValue / 5;
            if(cha > 0) {
                leftyAxisVoltage.setAxisMaximum(maxVoltageValue + cha);
            }
            else {
                leftyAxisVoltage.setAxisMaximum(300);
            }
            List<Entry> list = new ArrayList<>();
            for (int i = 0; i < voltageValues.length; i++) {
                list.add(new Entry((float) i, voltageValues[i]));
            }

            setVoltage.setValues(list);

            LineData data = new LineData(setVoltage);
            data.setDrawValues(false);
            data.setValueTextColor(Color.RED);
            data.setValueTextSize(15f);
            lineChartVoltage.setData(data);
            lineChartVoltage.invalidate();
        }
        else{
            setDataVoltage(lineChartVoltage,voltageValues);
        }




        if(setElectricA != null) {
            int cha = maxElectricValue  / 5;
            if(cha > 0 ) {
                leftyAxisElectric.setAxisMaximum(maxElectricValue + cha);
                rightAxisElectric.setAxisMaximum(maxElectricValue + cha);
            }
            else
            {
                leftyAxisElectric.setAxisMaximum(300);
                rightAxisElectric.setAxisMaximum(300);
            }
            List<Entry> listA = new ArrayList<>();
            List<Entry> listB = new ArrayList<>();
            List<Entry> listC = new ArrayList<>();
            for (int i = 0; i < electricA.length; i++) {
                listA.add(new Entry((float) i, electricA[i]));
                listB.add(new Entry((float) i, electricB[i]));
                listC.add(new Entry((float) i, electricC[i]));
            }

            setElectricA.setValues(listA);
            setElectricB.setValues(listB);
            setElectricC.setValues(listC);


            LineData data = new LineData(setElectricA,setElectricB,setElectricC);
            data.setDrawValues(false);
            data.setValueTextColor(Color.RED);
            data.setValueTextSize(15f);
            lineChartElectric.setData(data);
            lineChartElectric.invalidate();
        }
        else {
            setDataElectric(lineChartElectric, electricA, electricB,electricC);
        }
        resetWidth(new Float(leftyAxisVoltage.getAxisMaximum()).intValue(),new Float(leftyAxisElectric.getAxisMaximum()).intValue());
    }

    public  void resetData(TotalPopDataChangedEvent event){
        if(!isFinding)
        {
            resetData(event.getMaxVoltageValue(),event.getMaxElectricValue(),event.getVoltageValues(),event.getElectricValueA(),event.getElectricValueB(),event.getElectricValueC());
        }
    }

    public  void setDataElectric(LineChart lineChart,int[] electricValuesA,int[] electricValuesB,int[] electricValuesC){

        lineChart.setNoDataText("");
        int count = electricValuesA.length;
        TotalData.readTotal(count);
        this.lineChartElectric = lineChart;
        List<Entry> listA = new ArrayList<>();
        List<Entry> listB = new ArrayList<>();
        List<Entry> listC = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            listA.add(new Entry((float)i,electricValuesA[i]));
            listB.add(new Entry((float)i,electricValuesB[i]));
            listC.add(new Entry((float)i,electricValuesC[i]));
        }

        setElectricA = new LineDataSet(listA,"Ia");
        setElectricB = new LineDataSet(listB,"Ib");
        setElectricC = new LineDataSet(listC,"Ic");

        // set.setColor(Color.WHITE);
        // set2.setColor(Color.WHITE);
        Legend legend1 = lineChart.getLegend();
        legend1.setTextColor(Color.WHITE);
        legend1.setTextSize(18f);

        legend1.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend1.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend1.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);

        //标志在文字的位置--左侧
        legend1.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);

        Description description = lineChart.getDescription();
        description.setEnabled(false);
        lineChart.setDescription(description);

        setElectricA.setLineWidth(4f);
        setElectricA.setCircleRadius(1.5f);
        setElectricA.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        setElectricA.setCircleColor(Color.rgb(255,255,0));
        setElectricA.setColor(Color.rgb(255,255,0));
        setElectricA.setDrawFilled(false);
        setElectricA.setDrawCircleHole(false);
        setElectricA.setValueTextSize(10f);

        setElectricB.setLineWidth(4f);
        setElectricB.setCircleRadius(1.5f);
        setElectricB.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        setElectricB.setCircleColor(Color.rgb(0,255,0));
        setElectricB.setColor(Color.rgb(0,255,0));
        setElectricB.setDrawFilled(false);
        setElectricB.setDrawCircleHole(false);
        setElectricB.setValueTextSize(10f);

        setElectricC.setLineWidth(4f);
        setElectricC.setCircleRadius(1.5f);
        setElectricC.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        setElectricC.setCircleColor(Color.rgb(255,0,0));
        setElectricC.setColor(Color.rgb(255,0,0));
        setElectricC.setDrawFilled(false);
        setElectricC.setDrawCircleHole(false);
        setElectricC.setValueTextSize(10f);

        lineDataElectric = new LineData(setElectricA,setElectricB,setElectricC);
        lineDataElectric.setDrawValues(false);
        lineDataElectric.setValueTextColor(Color.RED);
        lineDataElectric.setValueTextSize(15f);



        lineChart.getXAxis().setDrawGridLines(false);
        lineChart.getXAxis().setEnabled(false);

        rightAxisElectric =lineChart.getAxisRight();
        rightAxisElectric.setDrawAxisLine(true);
        rightAxisElectric.setLabelCount(10);
        rightAxisElectric.setDrawLabels(true);
        rightAxisElectric.setDrawZeroLine(true);
        rightAxisElectric.setDrawGridLines(false);
        rightAxisElectric.setTextColor(Color.rgb(0x04,0xAD,0xFF));
        rightAxisElectric.setAxisLineColor(Color.rgb(0x04,0xAD,0xFF));
        rightAxisElectric.setGridColor(LineChatUtils.GridColor);
        rightAxisElectric.setAxisMaximum(300f);
        rightAxisElectric.setAxisMinimum(0f);

        leftyAxisElectric = lineChart.getAxisLeft();
        leftyAxisElectric.setDrawGridLines(false);
        leftyAxisElectric.setAxisMinimum(0f);
        leftyAxisElectric.setAxisMaximum(300f);
        leftyAxisElectric.setEnabled(false);
        leftyAxisElectric.setTextColor(Color.WHITE);
        lineChart.setData(lineDataElectric);

    }


    public  void setDataVoltage(LineChart lineChart,int[] voltageValues) {
        int count = voltageValues.length;
        TotalData.readTotal(count);
        this.lineChartVoltage = lineChart;
        List<Entry> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            list.add(new Entry((float)i,voltageValues[i]));
        }
        lineChart.setNoDataText("");
        setVoltage = new LineDataSet(list,"电压值");

        // set.setColor(Color.WHITE);
        // set2.setColor(Color.WHITE);
        Legend legend1 = lineChart.getLegend();
        legend1.setTextColor(Color.WHITE);
        legend1.setTextSize(18f);

        legend1.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend1.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend1.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);

        //标志在文字的位置--左侧
        legend1.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);

        Description description = lineChart.getDescription();
        description.setEnabled(false);
        lineChart.setDescription(description);
        setVoltage.setLineWidth(4f);
        setVoltage.setCircleRadius(1.5f);
        setVoltage.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        setVoltage.setCircleColor(Color.rgb(255,255,255));
        setVoltage.setColor(Color.rgb(255,255,255));
        setVoltage.setDrawFilled(false);
        setVoltage.setDrawCircleHole(false);
        setVoltage.setValueTextSize(10f);

        lineDataVoltage = new LineData(setVoltage);
        lineDataVoltage.setDrawValues(false);
        lineDataVoltage.setValueTextColor(Color.RED);
        lineDataVoltage.setValueTextSize(15f);

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setEnabled(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        // xAxis.setLabelCount(count);
        xAxis.setLabelCount(0);
        xAxis.setTextSize(8f);
        xAxis.setTextColor(Color.rgb(0x04,0xAD,0xFF));
        xAxis.setDrawAxisLine(true);
        xAxis.setDrawGridLines(false);

        xAxis.setAxisLineColor(Color.rgb(0x04,0xAD,0xFF));
        xAxis.setGridColor(LineChatUtils.GridColor);

        ValueFormatter valueFormatter = new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return ""+getLabel((int)value);
            }
        };
        xAxis.setValueFormatter(valueFormatter);

        leftyAxisVoltage =lineChart.getAxisLeft();
        leftyAxisVoltage.setDrawAxisLine(true);
        leftyAxisVoltage.setLabelCount(10);
        leftyAxisVoltage.setDrawLabels(true);
        leftyAxisVoltage.setDrawZeroLine(true);
        leftyAxisVoltage.setDrawGridLines(false);
        leftyAxisVoltage.setTextColor(Color.rgb(0x04,0xAD,0xFF));
        leftyAxisVoltage.setAxisLineColor(Color.rgb(0x04,0xAD,0xFF));
        leftyAxisVoltage.setGridColor(Color.rgb(255,255,255));
        leftyAxisVoltage.setAxisMaximum(600f);
        leftyAxisVoltage.setAxisMinimum(0f);
        YAxis rightyAxis = lineChart.getAxisRight();
        rightyAxis.setEnabled(false);
        lineChart.setData(lineDataVoltage);
    }

    private static String getLabel(int index)
    {
        int jiange = APPSPUtils.getInstance().getChatRefreshTime();
        Calendar calendar = Calendar.getInstance();
        Log.d("SHOOTLEE","currentECCount"+jiange);
        calendar.add(Calendar.SECOND, (index * jiange - 10 * jiange));
        return formatter.format(calendar.getTime());
    }

    private static DateFormat formatter = new SimpleDateFormat("mm:ss");

    public void close()
    {
        this.lineChartVoltage.clearAnimation();
        this.lineChartElectric.clearAnimation();
    }

    private void resetWidth(int maxVoltageValue,int maxElectricValue)
    {

        Log.d("RealViewTotalData","MAX V:"+maxVoltageValue+" ||| MAX E:"+maxElectricValue);
        int newWidthVoltage,newLeftVoltage ,newWidthElectric,newLeftElectric;
        newLeftVoltage = defaultLeftVoltage;
        if(maxVoltageValue >= 10000)
        {
            newLeftElectric = 45;
            newWidthElectric = defaultWidthElectric - 20;
        }
        else if(maxVoltageValue >= 1000)
        {
            newLeftElectric = 40;
            newWidthElectric = defaultWidthElectric - 10;
        }
        else
        {
            newLeftElectric = 30;
            newWidthElectric = defaultWidthElectric;
        }

        if(maxElectricValue >= 10000)
        {

            newWidthVoltage = defaultWidthVoltage - 20;
        }
        else if(maxElectricValue >= 1000)
        {

            newWidthVoltage = defaultWidthVoltage - 10;
        }
        else
        {

            newWidthVoltage = defaultWidthVoltage;
        }
        checkAndSet(newWidthVoltage,newLeftVoltage,newWidthElectric,newLeftElectric);

    }


    private void checkAndSet(int newWidthVoltage,int newLeftVoltage,int newWidthElectric,int newLeftElectric){
        if(newWidthVoltage != currentWidthVoltage || newLeftVoltage != currentLeftVoltage)
        {
            ViewGroup.MarginLayoutParams params =  (ViewGroup.MarginLayoutParams) this.lineChartVoltage.getLayoutParams();
            params.width = newWidthVoltage;
            params.leftMargin = newLeftVoltage;

            Log.d("RealViewTotalData","SET NEW VO,W:"+params.width+"  LM:"+params.leftMargin);

            this.lineChartVoltage.setLayoutParams(params);
            currentWidthVoltage = newWidthVoltage;
            currentLeftVoltage = newLeftVoltage;
        }
        if(newWidthElectric != currentWidthElectric || newLeftElectric != currentLeftElectric){
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) this.lineChartElectric.getLayoutParams();
            params.width = newWidthElectric;
            params.leftMargin = newLeftElectric;
            Log.d("RealViewTotalData","SET NEW EL,W:"+params.width+"  LM:"+params.leftMargin);
            this.lineChartElectric.setLayoutParams(params);
            currentWidthElectric = newWidthElectric;
            currentLeftElectric = newLeftElectric;
        }
    }

    boolean isFinding = false;

    public void find(MyCalendar date)
    {
        isFinding = true;
        Log.d("SHOOTLEEFIND","开始");
        int count = 600;
        int[] arrayV = new int[count];
        int[] arrayE = new int[count];
        int[] arrayEA = new int[count];
        int[] arrayEB = new int[count];
        int[] arrayEC = new int[count];

        long beginTime = date.getTimestamp();
        long endTime = beginTime+ 1000 * 60 * 11 ;
        Log.d("SHOOTLEEFIND","开始2");
        int countA =  LitePal.count(NewTotalDataEntity.class);
        Log.d("SHOOTLEEFIND","开始2,,,"+countA);
        List<NewTotalDataEntity> ls =   LitePal.where("createTime > ? AND createTime < ?",String.valueOf(beginTime),String.valueOf(endTime)).find(NewTotalDataEntity.class);

        int forCount = count;

        Log.d("SHOOTLEEFIND","开始3,,,"+ls.size());
        if(ls.size() < forCount)
        {
            forCount = ls.size();
        }
        Log.d("SHOOTLEEFIND","开始4");
        for(int i = 0;i< forCount;i++)
        {
            NewTotalDataEntity entity = ls.get(i);
            arrayV[i] = (entity.getVoltageA() + entity.getVoltageB() + entity.getVoltageC()) /3;
            arrayE[i] = (entity.getElectricA() + entity.getElectricB() + entity.getElectricC()) /3;
            arrayEA[i] = entity.getElectricA();
            arrayEB[i] = entity.getElectricB();
            arrayEC[i] = entity.getElectricC();
        }


        Log.d("SHOOTLEEFIND","开始5");

        TotalPopDataChangedEvent event = new TotalPopDataChangedEvent(arrayV,arrayE,arrayEA,arrayEB,arrayEC);

        resetData(event.getMaxVoltageValue(),event.getMaxElectricValue(),event.getVoltageValues(), event.getElectricValueA(), event.getElectricValueB(),event.getElectricValueC());
        Log.d("SHOOTLEEFIND","结束");
    }
    public void unfind()
    {
        isFinding = false;
    }
}
